package com.group3.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.group3.common.result.ApiResponse;

import com.group3.model.Product;
import com.group3.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/products")
public class ProductController {

    private final ProductService productService = new ProductService();

    // 查询所有商品
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }


    @GetMapping("/products/getByPids")
    ApiResponse<List<Product>> getProductsByPids(@RequestParam List<Integer> pids){

         return ApiResponse .success(productService.getProductsByPids(pids));
    }
    // 根据商品ID查询商品
    @SentinelResource(value = "hot_product")
    @GetMapping("/{pid}")
    public Optional<Product> getProductById(@PathVariable Integer pid) {

        return productService.getProductById(pid);
    }

    // 新增商品
    @PostMapping
    public void addProduct(@RequestBody Product product) {
        productService.addProduct(product);
    }

    // 更新商品信息

    @PutMapping("/{pid}")
    public boolean updateProduct(@PathVariable Integer pid, @RequestBody Product updatedProduct) {
        return productService.updateProduct(pid, updatedProduct);
    }

    // 删除商品
    @DeleteMapping("/{pid}")
    public boolean deleteProduct(@PathVariable Integer pid) {
        return productService.deleteProduct(pid);
    }

    // 扣减库存


    @RequestMapping("/decreaseStock")

    public boolean decreaseStock(@RequestParam Integer pid, @RequestParam Integer number) {
        log .info("扣减库存{}",pid);
        return productService.decreaseStock(pid, number);
    }


    // 增加库存
    @RequestMapping("/increaseStock")
    public boolean increaseStock(@RequestParam Integer pid, @RequestParam Integer number) {

        return productService.increaseStock(pid, number);
    }

    // 上架商品（状态设为1）
    @PostMapping("/publish/{pid}")
    public ApiResponse publishProduct(@PathVariable Integer pid) {
        boolean result = productService.updateProductStatus(pid, 1);
        return result ? ApiResponse.success("商品上架成功") : ApiResponse.error("商品上架失败");
    }

    // 下架商品（状态设为0）
    @PostMapping("/unpublish/{pid}")
    public ApiResponse unpublishProduct(@PathVariable Integer pid) {
        boolean result = productService.updateProductStatus(pid, 0);
        return result ? ApiResponse.success("商品下架成功") : ApiResponse.error("商品下架失败");
    }
}
